using System;
using System.Collections;
using System.Collections.Generic;
using System.Xml;
using Flaschengeist.DataAccess;
using Flaschengeist.Entities;
using Flaschengeist.Views;
using UnityEngine;

namespace Flaschengeist.Processes 
{
	public class LoadWorlds : MonoBehaviour
	{
		private XmlRpc xmlrpc;
		private ErrorView errorView;
		
		public void Start()
		{			
			errorView = gameObject.GetComponent<ErrorView>();
			xmlrpc = gameObject.AddComponent<XmlRpc>();
			xmlrpc.Completed += LoadCompleted;
		}
		
		private void LoadCompleted(string xml)
		{
			var worlds = new List<World>();
			
			foreach (XmlNode item in xml.GetRecords())
			{
				var world = new World();
								
				foreach (XmlNode node in item.ChildNodes) 
				{
					if (node.HasChildNodes)
					{
						if(node.FirstChild.InnerText == "Id")
							world.Id = int.Parse(node.LastChild.GetValueFromNode());
						
						if(node.FirstChild.InnerText == "Genre")
							world.Genre = node.LastChild.GetValueFromNode();	
														
						if(node.FirstChild.InnerText == "Scale")
							world.Scale = node.LastChild.GetValuesFromNode();								
					}				
				}
										
				worlds.Add(world);
			}
			Debug.Log("Finish load Worlds");
			Completed(worlds);
		}
		
		public void Process()
		{
			try 
			{
				Debug.Log("Start load Worlds");
				xmlrpc.Process("getWorlds", new Hashtable());
			} 
			catch (Exception ex) 
			{
				errorView.Show(ex);
			}
		}
					
		public event Action<IEnumerable<World>> Completed;
	}
}

